<template>
    <div class="edit-container" v-loading="loading">
        <div class="info-div base-info-good">
            <div class="div-title-good">
              基础信息
              <div class="title-btn-bar">
                <el-button type="primary" @click="syncImgParams.isShow=true">同步商品图片</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
              </div>
            </div>
            <el-form ref="form" :model="form" label-width="140px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="商品名称" prop="goodsName">
                            <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="商品系列名称" prop="seriesName">
                            <el-input v-model="form.seriesName" placeholder="请输入商品系列名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="平台基准价格" prop="price">
                            <el-input type="number" v-model="form.price" placeholder="请输入平台基准价格" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商店成本价格" prop="costPrice">
                            <el-input type="number" v-model="form.costPrice" placeholder="请输入商店成本价格" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="商品编号" prop="goodsSn">
                            <el-input v-model="form.goodsSn" placeholder="请输入商品编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品排序" prop="sort">
                            <el-input type="number" v-model="form.sort" placeholder="请输入商品排序" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="商品分类" prop="catId">
                            <el-select v-model="form.catId" placeholder="请选择商品分类">
                                <el-option
                                v-for="dict in categoryOptions"
                                :key="dict.id"
                                :label="dict.catName"
                                :value="dict.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否上架">
                            <el-select v-model="form.isOnSale" placeholder="请选择是否上架">
                                <el-option
                                v-for="dict in isActiveOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="商品系列" prop="seriesId">
                            <el-select v-model="form.seriesId" placeholder="请选择商品系列">
                                <el-option
                                v-for="dict in isActiveOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否在列表显示" prop="goodsListShow">
                            <el-select v-model="form.goodsListShow" placeholder="请选择是否显示">
                                <el-option
                                v-for="dict in isActiveOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品供应商" prop="goodsSupplierName">
                            <el-select v-model="form.goodsSupplierName" placeholder="请选择是否显示">
                                <el-option
                                v-for="dict in gysOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="商品简介" prop="goodsDesc">
                            <el-input type="textarea" v-model="form.goodsDesc" placeholder="请输入商品详情" rows="8" resize="vertical"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="info-div">
            <div class="div-title-good">商品属性库存</div>
            <div class="goods-attrs-btn-bar">
                <el-button type="primary" @click="addGoodsAttr">添加商品库存</el-button>
            </div>
            <div class="goods-attrs-list">
                <el-table :data="goodsAttrs" style="width: 100%">
                    <el-table-column prop="attrValue" label="属性1" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.attrValue" type="text" placeholder="请选择属性1"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="attrValue2" label="属性2" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.attrValue2" type="text" placeholder="请选择属性2"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="attrValue3" label="属性3" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.attrValue3" type="text" placeholder="请选择属性3"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="attrGoodsNumber" label="库存" align="center" width="120">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.attrGoodsNumber" type="number" placeholder="请输入库存数"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="delGoodsAttr(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

        </div>

        <div class="info-div main-pic">
            <div class="div-title-good">商品主图片</div>
            <div class="pic-div">
                <el-upload :action="uploadActionMain" :headers="uploadHeaders" :multiple="true" :file-list="mainPic" list-type="picture-card" :on-success="handleUploadSuccMain">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handlePicRemove(file, mainPic)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
            </div>
        </div>

        <div class="info-div swiper-pic">
            <div class="div-title-good">商品轮播图</div>
            <div class="pic-div">
                <el-upload :action="uploadActionSwiper" :headers="uploadHeaders" :multiple="true" :file-list="swiperPic" list-type="picture-card" :on-success="handleUploadSuccSwiper">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handlePicRemove(file, swiperPic)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
            </div>
        </div>

        <div class="info-div spec-pic">
            <div class="div-title-good">商品规格图</div>
            <div class="pic-div">
                <el-upload :action="uploadActionSpec" :headers="uploadHeaders" :multiple="true" :file-list="specPic" list-type="picture-card" :on-success="handleUploadSuccSpec">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handlePicRemove(file, specPic)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
            </div>
        </div>

        <div class="info-div describe-pic">
            <div class="div-title-good">商品描述图</div>
            <div class="pic-div">
                <div class="upload-area">
                    <el-upload :action="uploadActionDescribe" :data="{sorting:describePic.length}" :headers="uploadHeaders" :multiple="true" list-type="picture-card" :before-upload="handleBeforeUploadDescribe" :on-success="handleUploadSuccDescribe" :show-file-list="false"><!-- :file-list="describePic" -->
                        <i slot="default" class="el-icon-plus"></i>
                        <div slot="file" slot-scope="{file}" draggable="true">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                                    <i class="el-icon-zoom-in"></i>
                                </span>
                                <span class="el-upload-list__item-delete" @click="handlePicRemove(file, describePic)">
                                    <i class="el-icon-delete"></i>
                                </span>
                                <span class="el-upload-list__item-up" @click="handleDescribePicMove('up', file, describePic)">
                                    <i class="el-icon-top"></i>
                                </span>
                                <span class="el-upload-list__item-down" @click="handleDescribePicMove('down', file, describePic)">
                                    <i class="el-icon-bottom"></i>
                                </span>
                            </span>
                        </div>
                    </el-upload>
                    <div class="describe-img-item" v-for="item in describePic" :key="item.$index">
                        <div class="describe-img-item-content">
                            <img :src="item.url" v-if="item.fileType!='mp4'"/>
                            <video :src="item.url" v-if="item.fileType=='mp4'" controls></video>
                            <span class="item-actions">
                                <span class="item-preview" @click="handlePicPreview(item)">
                                    <i class="el-icon-zoom-in"></i>
                                </span>
                                <span class="item-delete" @click="handleDesPicRemove(item, describePic)">
                                    <i class="el-icon-delete"></i>
                                </span>
                                <span class="item-up" @click="handleDescribePicMove('up', item, describePic)">
                                    <i class="el-icon-top"></i>
                                </span>
                                <span class="item-down" @click="handleDescribePicMove('down', item, describePic)">
                                    <i class="el-icon-bottom"></i>
                                </span>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="preview-area"></div>
            </div>
        </div>

        <div class="info-div">
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>

        <el-dialog :visible.sync="showPicPreview">
            <img width="100%" :src="picPreviewUrl" alt="">
        </el-dialog>

        <el-dialog class="syncImg" :visible.sync="syncImgParams.isShow" v-loading.sync="syncImgParams.loading">
            <el-form class="sync-img-form" label-width="100px" :inline="true">
              <el-form-item label="商品ID" prop="goodsId">
                <el-input v-model="syncImgParams.goodsId" placeholder="请输入商品ID" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGetImgData">查 询</el-button>
              </el-form-item>
            </el-form>
            <div class="sync-img-list-box">
              <div class="sync-img-list-title" v-if="syncImgParams.imgData.main">主图</div>
              <div class="sync-img-list" v-if="syncImgParams.imgData.main">
                <div class="sync-img-item" v-for="item in syncImgParams.imgData.main" :key="item.$index">
                    <img :src="imgUrl+item"/>
                    <span class="item-actions">
                        <span class="item-preview" @click="handlePicPreview({url:(imgUrl+item)})">
                            <i class="el-icon-zoom-in"></i>
                        </span>
                    </span>
                </div>
              </div>
              <div class="sync-img-list-title" v-if="syncImgParams.imgData.gallery">轮播图</div>
              <div class="sync-img-list" v-if="syncImgParams.imgData.gallery">
                <div class="sync-img-item" v-for="item in syncImgParams.imgData.gallery" :key="item.$index">
                    <img :src="imgUrl+item"/>
                    <span class="item-actions">
                        <span class="item-preview" @click="handlePicPreview({url:(imgUrl+item)})">
                            <i class="el-icon-zoom-in"></i>
                        </span>
                    </span>
                </div>
              </div>
              <div class="sync-img-list-title" v-if="syncImgParams.imgData.desc">规格图</div>
              <div class="sync-img-list" v-if="syncImgParams.imgData.desc">
                <div class="sync-img-item" v-for="item in syncImgParams.imgData.desc" :key="item.$index">
                    <img :src="imgUrl+item"/>
                    <span class="item-actions">
                        <span class="item-preview" @click="handlePicPreview({url:(imgUrl+item)})">
                            <i class="el-icon-zoom-in"></i>
                        </span>
                    </span>
                </div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer" v-if="syncImgParams.imgData.main">
              <el-button type="primary" @click="handleSubmitSyncImg">同 步</el-button>
              <el-button @click="handleCancelSyncImg">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import axios from 'axios'
    import { getId } from "@/api/common"
    import { getGoods, addGoods, updateGoods, getGoodsImgInfo, getScGoodsInfo } from "@/api/goods/goods";
    import { listAttrAll, addAttr, updateAttr } from "@/api/goodsAttr/attr";
    import { listCategoryAll } from "@/api/category/category";
    import { addFile, delFiles, getFileList, editFile, uploadFileByUrl } from "@/api/basic/file"

    export default {
        name: "GoodsEdit",
        data() {
            return {
                imgUrl:'https://img.huanai.com/',
                goodsId:"",
                // 遮罩层
                loading: false,
                // 表单参数
                form: {},
                // 表单校验
                rules: {

                },
                mainPic:[],
                swiperPic:[],
                specPic:[],
                describePic:[],
                uploadActionMain:"",
                uploadActionSwiper:"",
                uploadActionSpec:"",
                uploadActionDescribe:"",
                uploadHeaders: {
                    Authorization: 'Bearer ' + this.$store.state.user.token,
                    lesseeId: this.$store.state.user.lesseeid
                },
                showPicPreview:false,
                picPreviewUrl:"",
                isActiveOptions:[],
                categoryOptions:[],
                oldGoodsAttrs:[],
                goodsAttrs:[],
                unActivedGoodsAttrs:[],
                attrsOptions:[],
                gysOptions:[],
                syncImgParams:{
                  isShow:false,
                  goodsId:'',
                  goodsInfo:{},
                  imgData:{},
                  loading:false
                }
            };
        },
        created() {
            if(this.$route.params.id == "new"){
                this.createId(res =>{
                    this.goodsId = res
                    this.form.id = res
                    this.setUploadAction(this.goodsId)
                })
            }else{
                this.goodsId = this.$route.params.id
                this.getAttr(this.goodsId)
                this.getGoodsInfo(this.goodsId)
                this.getAllFileList(this.goodsId)
                this.setUploadAction(this.goodsId)
            }

            this.getGoodsCategory()

            this.getDicts("is_active").then(response => {
                this.isActiveOptions = response.data;
            });
            this.getDicts("YD_GYS_LIST").then(response => {
                this.gysOptions = response.data;
            });

        },
        methods: {
            getScGoodsInfo(goodsId){
              getScGoodsInfo({goodsId}).then(res=>{
                this.syncImgParams.goodsInfo = res.data
              })
            },
            handleShowSyncImg(){
              this.syncImgParams.imgData = {}
              this.syncImgParams.isShow = true
            },
            uploadSyncImgMain(call){
              let nssFile = {
                sourcessId: this.goodsId,
                sourcessType: "GOODS_INFO",
                sourcessType2: "MAIN",
                upFileUrl: (this.imgUrl+this.syncImgParams.imgData.main[0])
              }
              uploadFileByUrl({buName:'goods', nssFile}).then(res=>{
                this.handleUploadSuccMain(res, {name: res.fileName, url: res.url, id: res.fileId})
                if(call){
                    call()
                }
              }).catch(()=>{})
            },
            uploadSyncImgGallery(url, call){
                let nssFile = {
                    sourcessId: this.goodsId,
                    sourcessType: "GOODS_INFO",
                    sourcessType2: "SWIPER",
                    upFileUrl: (this.imgUrl + url)
                }
                uploadFileByUrl({buName:'goods', nssFile}).then(res=>{
                    this.swiperPic.push({name: res.fileName, url: res.url, id: res.fileId})
                    if(call){
                        call()
                    }
                }).catch(()=>{})
            },
            uploadSyncImgDesc(url, call){
                let nssFile = {
                    sourcessId: this.goodsId,
                    sourcessType: "GOODS_INFO",
                    sourcessType2: "DESCRIBE",
                    upFileUrl: (this.imgUrl + url)
                }
                uploadFileByUrl({buName:'goods', nssFile}).then(res=>{
                    this.describePic.push({name: res.fileName, url: res.url, id: res.fileId})
                    if(call){
                        call()
                    }
                }).catch(()=>{})
            },
            handleSubmitSyncImg(){
              /* this.uploadActionMain = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=MAIN"
                this.uploadActionSwiper = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=SWIPER"
                this.uploadActionSpec = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=SPEC"
                this.uploadActionDescribe = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=DESCRIBE" */
                this.syncImgParams.loading = true
                let totalCount = 0
                if(this.syncImgParams.imgData.main){
                    totalCount = 1
                    this.uploadSyncImgMain(()=>{
                        totalCount--
                        if(totalCount==0){
                            this.syncImgParams.loading = false
                            this.syncImgParams.isShow = false
                            this.msgSuccess("同步成功")
                        }
                    })
                }
                if(this.syncImgParams.imgData.gallery){
                    totalCount = totalCount+this.syncImgParams.imgData.gallery.length
                    for(let i of this.syncImgParams.imgData.gallery){
                        this.uploadSyncImgGallery(i, ()=>{
                            totalCount--
                            if(totalCount==0){
                                this.syncImgParams.loading = false
                                this.syncImgParams.isShow = false
                                this.msgSuccess("同步成功")
                            }
                        })
                    }
                }
                if(this.syncImgParams.imgData.desc){
                    totalCount = totalCount+this.syncImgParams.imgData.desc.length
                    for(let i of this.syncImgParams.imgData.desc){
                        this.uploadSyncImgDesc(i, ()=>{
                            totalCount--
                            if(totalCount==0){
                                this.syncImgParams.loading = false
                                this.syncImgParams.isShow = false
                                this.msgSuccess("同步成功")
                            }
                        })
                    }
                }
                console.log(this.syncImgParams.goodsInfo)
                if(this.syncImgParams.goodsInfo){
                  this.form.goodsName = this.syncImgParams.goodsInfo.goods_name
                  this.form.price = this.syncImgParams.goodsInfo.shop_price
                  this.form.costPrice = this.syncImgParams.goodsInfo.shop_price
                  this.form.isOnSale = '1'
                  this.form.goodsListShow = '1'
                  if(this.syncImgParams.goodsInfo.attr_list&&this.syncImgParams.goodsInfo.attr_list.length){
                    this.goodsAttrs = []
                    for(let i of this.syncImgParams.goodsInfo.attr_list){
                      this.goodsAttrs.push({
                        attrGoodsNumber:0,
                        attrValue:i.attr_value,
                        attrValue2:"",
                        attrValue3:"",
                        goodsId:this.goodsId
                      })
                    }
                  }

                }
            },
            handleCancelSyncImg(){
              this.syncImgParams.isShow = false
            },
            handleGetImgData(){
              if(this.syncImgParams.goodsId){
                this.syncImgParams.loading = true
                this.getScGoodsInfo(this.syncImgParams.goodsId)
                getGoodsImgInfo({goodsId: this.syncImgParams.goodsId}).then(res=>{
                  let main = []
                  let gallery = []
                  let desc = []
                  main.push(res.thumb)
                  for(let i of res.gallery){
                    gallery.push(i.thumb_url)
                  }
                  for(let j of res.desc){
                    desc.push(JSON.parse(j))
                  }
                  this.syncImgParams.imgData = {
                    main,
                    gallery,
                    desc
                  }
                  this.syncImgParams.loading = false
                }).catch(()=>{
                  this.syncImgParams.loading = false
                })
              }
            },

            createId(call){
                getId().then(response => {
                    if(call){
                        call(response.data.id)
                    }
                })
            },

            handleUploadSuccMain(response, file, fileList){
                if(this.mainPic.length){
                    let fileId = this.mainPic[0].id || this.mainPic[0].response.fileId
                    delFiles({ids:fileId}).then(response => {})
                }
                this.mainPic = [file]
                this.form.goodsImg = response.url
            },
            handleUploadSuccSwiper(response, file, fileList){
                this.swiperPic = fileList
            },
            handleUploadSuccSpec(response, file, fileList){
                this.specPic = fileList
            },
            handleUploadSuccDescribe(response, file, fileList){
                this.describePic.push({name: response.fileName, url: response.url, id: response.fileId, fileType:response.fileName.slice(response.fileName.lastIndexOf(".")+1)})
                this.loading = false;
            },
            handleBeforeUploadDescribe(){
                this.loading = true
            },

            handlePicPreview(file){
                this.picPreviewUrl = file.url
                this.showPicPreview = true
            },

            handlePicRemove(file, fileList){
                return this.$confirm('确定删除该图片?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let fileId = file.id||(file.response.fileId)
                    if(fileId){
                        delFiles({ids:fileId}).then(response => {
                            if (response.code !== 200) {
                                this.msgError(response.msg)
                            }else{
                                let findIndex = fileList.findIndex(obj=>{
                                    return obj.uid == file.uid
                                })
                                if(findIndex>=0){
                                    fileList.splice(findIndex,1)
                                }
                            }
                        })
                    }else{
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        let findIndex = fileList.findIndex(obj=>{
                            return obj.uid == file.uid
                        })
                        if(findIndex>=0){
                            fileList.splice(findIndex,1)
                        }
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            handleDesPicRemove(file, fileList){
                return this.$confirm('确定删除该图片?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let fileId = file.id
                    if(fileId){
                        delFiles({ids:fileId}).then(response => {
                            if (response.code !== 200) {
                                this.msgError(response.msg)
                            }else{
                                let findIndex = fileList.findIndex(obj=>{
                                    return obj.id == file.id
                                })
                                if(findIndex>=0){
                                    fileList.splice(findIndex,1)
                                }
                            }
                        })
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            editFile(file, sorting){
                editFile({id:(file.id || file.response.fileId), sorting}, res=>{})
            },

            handleDescribePicMove(flag, file, fileList){
                let index = fileList.findIndex(obj => {
                    return obj.uid == file.uid
                })
                if(flag == "up"){
                    if(index > 0){
                        let arr1 = fileList.slice(0, index-1)
                        let arr2 = fileList.slice(index+1)
                        this.describePic = arr1.concat([fileList[index], fileList[index-1]]).concat(arr2)
                        /* this.editFile(fileList[index], index-1)
                        this.editFile(fileList[index-1], index) */
                    }
                }else if(flag == "down"){
                    if(index < (fileList.length-1)){
                        let arr1 = fileList.slice(0, index)
                        let arr2 = fileList.slice(index+2)
                        this.describePic = arr1.concat([fileList[index+1], fileList[index]]).concat(arr2)
                        /* this.editFile(fileList[index], index+1)
                        this.editFile(fileList[index+1], index) */
                    }
                }
            },

            setUploadAction(id){
                this.uploadActionMain = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=MAIN"
                this.uploadActionSwiper = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=SWIPER"
                this.uploadActionSpec = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=SPEC"
                this.uploadActionDescribe = process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=GOODS_INFO&sourcessType2=DESCRIBE"
            },

            getGoodsCategory(){
                listCategoryAll({goodsListShow:'1'}).then(response => {
                    if (response.code === 200) {
                        this.categoryOptions = response.data
                    }
                })
            },

            getGoodsInfo(id){
                getGoods(id).then(response => {
                    this.form = response.data;
                });
            },

            getFileList(id,sourcessType,sourcessType2,call){
                let params = {sourcessId:id,sourcessType,sourcessType2}
                getFileList(params).then(response => {
                    if (response.code === 200) {
                        if(call){
                            call(response.rows)
                        }
                    }
                })
            },

            getAllFileList(id){
                this.getFileList(id,"GOODS_INFO","MAIN",res=>{
                    for(let i of res){
                        this.mainPic.push({name: i.fileObjectName, url: i.fileFullUrl, id: i.id})
                    }
                })
                this.getFileList(id,"GOODS_INFO","SWIPER",res=>{
                    for(let i of res){
                        this.swiperPic.push({name: i.fileObjectName, url: i.fileFullUrl, id: i.id})
                    }
                })
                this.getFileList(id,"GOODS_INFO","SPEC",res=>{
                    for(let i of res){
                        this.specPic.push({name: i.fileObjectName, url: i.fileFullUrl, id: i.id})
                    }
                })
                this.getFileList(id,"GOODS_INFO","DESCRIBE",res=>{
                    for(let i of res){
                        this.describePic.push({name: i.fileObjectName, url: i.fileFullUrl, id: i.id, fileType:i.fileType})
                    }
                })
            },

            submitForm(){
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if(!this.goodsAttrs.length){
                            this.msgError("请至少添加一条商品属性库存");
                            return
                        }
                        for(let i of this.goodsAttrs){
                            if(!i.attrValue && !i.attrValue2 && !i.attrValue3){
                                this.msgError("商品属性库存至少选择一个属性");
                                return
                            }
                            for(let j of this.goodsAttrs){
                                if(i!=j && i.attrValue == j.attrValue && i.attrValue2 == j.attrValue2 && i.attrValue3 == j.attrValue3){
                                    this.msgError("商品属性库存有重复，请检查后再提交");
                                    return
                                }
                            }
                        }
                        if (this.$route.params.id != "new") {
                            updateGoods(this.form).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("修改成功");
                                    for(let i in this.describePic){
                                        this.editFile(this.describePic[i], i)
                                    }
                                    this.submitGoodsAttr()
                                    this.$store.dispatch("tagsView/delView", this.$route).then(({ visitedViews }) => {
                                        this.$router.back()
                                    });
                                }
                            });
                        } else {
                            addGoods(this.form).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("新增成功");
                                    for(let i in this.describePic){
                                        this.editFile(this.describePic[i], i)
                                    }
                                    this.submitGoodsAttr()
                                    this.$store.dispatch("tagsView/delView", this.$route).then(({ visitedViews }) => {
                                        this.$router.back()
                                    });
                                }
                            });
                        }
                    }
                });
            },

            getAttr(goodsId){
                this.goodsAttrs = []
                listAttrAll({goodsId}).then(response => {
                    if (response.code !== 200) {
                        this.msgError(response.msg)
                    }else{
                        if(response.data.length>0){
                            this.goodsAttrs = JSON.parse(JSON.stringify(response.data))
                            this.oldGoodsAttrs = JSON.parse(JSON.stringify(response.data))
                        }
                    }
                })
            },

            addGoodsAttr(){
                this.goodsAttrs.push({
                    attrGoodsNumber:99999,
                    attrValue:"",
                    attrValue2:"",
                    attrValue3:"",
                    goodsId:this.goodsId
                })
            },
            delGoodsAttr(index, item){
                if(item.id){
                    item.isActive="0"
                    this.unActivedGoodsAttrs.push(item)
                }
                this.goodsAttrs.splice(index,1)
            },
            submitGoodsAttr(){
                let goodsAttrs = this.goodsAttrs.concat(this.unActivedGoodsAttrs)
                for(let i of goodsAttrs){
                    if(i.id){
                        let findObj = this.oldGoodsAttrs.find(obj => {
                            return obj.id == i.id && (obj.attrGoodsNumber != i.attrGoodsNumber || obj.attrValue != i.attrValue || obj.attrValue2 != i.attrValue2 || obj.attrValue3 != i.attrValue3 || obj.isActive != i.isActive)
                        })
                        console.log(findObj)
                        if(findObj){
                            updateAttr(i, res=>{})
                        }
                    }else if(i.isActive!='0'){
                        addAttr(i, res=>{})
                    }
                }

            }
        }
    }
</script>
<style>
    .info-div{
        padding: 20px;
    }
    .pic-div{
        border: 1px dotted #9e9e9e;
        border-radius: 10px;
        padding: 10px;
    }
    .describe-pic .el-upload.el-upload--picture-card{
      width: 400px;
    }
    .describe-img-item{
        position: relative;
        width: 400px;
    }
    .describe-img-item-content{
        position: relative;
        display: inline-block;
    }
    .describe-img-item img{
        max-width: 100%;
        height: auto;
    }
    .describe-img-item video{
        height: 500px;
        width: auto;
        margin: 0 auto;
    }
    .item-actions{
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        cursor: default;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0,0,0,0.5);
        transition: opacity .3s;
    }
    .item-actions::after{
        vertical-align: middle;
        display: inline-block;
        content: "";
        height: 100%;
    }
    .item-actions:hover {
        opacity: 1;
    }
    .item-actions span{
        display: none;
        cursor: pointer;
    }
    .item-actions:hover span{
        display: inline-block;
    }
    .div-title-good{
        margin-bottom: 20px;
        font-weight: bold;
        display: flex;
        justify-content: space-between;
    }


    .describe-pic .el-upload-list--picture-card .el-upload-list__item{
        display: block;
        width: 50%;
        height: auto;
        margin: 0;
        border: none;
        border-radius: 0;
    }
    .describe-pic .el-upload-list--picture-card .el-upload-list__item-thumbnail{
        vertical-align: top;
    }
    .describe-pic .el-upload--picture-card{
        margin-top: 20px;
        width: 50%;
        height: auto;
    }

    .el-dialog__body{
        padding: 10px 20px 30px 20px;
    }
    .attrs-btn-div{
        text-align: center;
        margin-top: 30px;
    }
    .goods-attrs-btn-bar{
        text-align: right;
        margin-bottom: 20px;
    }

    .sync-img-form{
      margin-top: 20px;
    }
    .sync-img-data-box{

    }
    .sync-img-list-title{

    }
    .sync-img-list{
      display: flex;
      flex-wrap: wrap;
      margin: 10px 0 30px 0;
    }
    .sync-img-item{
        position: relative;
        display: inline-block;
        width: 100px;
        height: 100px;
        margin: 0 10px 10px 0;
        border-radius: 6px;
        border: 1px solid #c0ccda;
    }
    .sync-img-item img{
        height: 100%;
        width: 100%;
        object-fit: contain;
        border-radius: 6px;
    }

    .syncImg .el-loading-mask{
        position: fixed;
    }
</style>

